<template>
    <view class="container">
        <view class="search-wrap">
            <view class="search-box">
                <uni-icons type="search" size="16" color="#666"></uni-icons>
                <input type="text"
                    v-model="keyword" placeholder="搜索"
                    placeholder-class="placeholder"
                    confirm-type="search"
                    @confirm="onRefresh" />
            </view>
        </view>

        <view class="main-content">
            <!-- 左侧分类导航 -->
            <view class="side-category">
                <view class="category-item"
                      :class="{ active: currentCategory === item.FId }"
                      v-for="item in categories"
                      :key="item.FId"
                      @tap="selectCategory(item.FId)">
                    {{ item.FTypeName }}
                </view>
            </view>

            <!-- 右侧内容区 -->
            <view class="right-content">
                <!-- 顶部横向分类 -->
                <view class="sub-category" v-if="false">
                    <scroll-view scroll-x="true" class="scroll-view">
                        <view class="nav-item"
                            :class="{ active: currentSubCategory === item.id }"
                            v-for="item in subCategories"
                            :key="item.id"
                            @tap="selectSubCategory(item.id)">
                            {{ item.name }}
                        </view>
                    </scroll-view>
                </view>

                <!-- 商品列表 -->
                <view class="product-list">
                    <view class="product-item" v-for="(item, index) in proList" :key="index" @tap="goDetail(item)">
                        <image class="product-img" :src="item.skuImg || item.proImg || '/static/errorImage.jpg'" lazy-load mode="aspectFill" />
                        <view class="product-info">
                            <view class="product-name">{{ item.proName }}</view>
                            <view class="zhima" v-if="item.zmFlag == '01'">
                                <image src="https://jdkj-1306681707.cos.ap-nanjing.myqcloud.com/S0000260/image/proImg_202505231011269767.png" class="zhima-icon"></image>
                                <span> 芝麻信用 | 免押金 </span>
                            </view>
                            <view class="product-desc">
                                <text>规格：{{ item.spec }}个/箱</text>
                            </view>
                            <view class="product-price">
                                <template v-if="item.activityPrice">
                                    <text class="price">
                                        {{ '￥' + item.activityPrice }}
                                        <text class="price-old" v-if="isGreater(item.userPrice, item.activityPrice)">
                                            {{item.userPrice}}
                                        </text>
                                    </text>
                                </template>
                                <template v-else>
                                    <text class="price">
                                        {{'￥' + (item.userPrice || '0')}}
                                        <text v-if="isGreater(item.originPrice, item.userPrice)" class="price-old">{{ '￥' + item.originPrice }}</text>
                                    </text>
                                </template>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLaunch, onLoad, onPullDownRefresh, } from '@dcloudio/uni-app';
import { getTypes, getProductSkuByTypeid } from '@/api/product';
import { useStore } from 'vuex';
const Store = useStore();


onPullDownRefresh(() => {
    onRefresh()
})



// 添加子分类状态
const currentSubCategory = ref('');
const subCategories = ref([ ]);
const selectSubCategory = (categoryId: string) => {
    currentSubCategory.value = categoryId;
};





const pageData = {
    storeNo: '',
    storeName: '',
    linkSysUserId: '',
}

onLoad((options: any) => {
    pageData.storeNo = options.storeNo || '';
    pageData.storeName = options.storeName || '';
    if(options.storeName) {
        uni.setNavigationBarTitle({
            title: options.storeName,
        });
    }
    pageData.linkSysUserId = options.linkSysUserId || '';
    Store.commit('shop/SET_TEMP_LINK_SYS_USERID', options.linkSysUserId || '');
    Store.commit('shop/SET_TEMP_STORE_NO', options.storeNo || '');

    console.log(Store.state.shop.tempLinkSysUserId);

    getTypeList();

});



type Category = {
    FId: string;
    FLink: string;
    FProStartNum: string;
    FProStartPrice: string;
    FSaleStatus: string;
    FTypeEndTime: string;
    FTypeIcon: string;
    FTypeImg: string;
    FTypeName: string;
    FTypeParentId: string;
    FTypeSort: string;
    FTypeStartTime: string;
    FUrlLink: string;
    child: any[];
};
const currentCategory = ref('');
const categories = ref<Category[]>([ ]);
const selectCategory = (categoryId: string) => {
    currentCategory.value = categoryId;
    onRefresh();
};

const getTypeList = () => {
    let data = {
        storeNo: pageData.storeNo || Store.state.shop.storeNo,
        typeKind: '00,01',  //01商品 00服务 13课程
        topFlag: '01',
        hasPro: '01',
        reatelSale: '01',
        destSysUserId: pageData.linkSysUserId || '',
    };
    getTypes(data).then(res => {
        try {
            let flist: Category[] = []
            const list = res.data || [];
            list.forEach((item: any) => {
                if (!item.FTypeParentId || item.FTypeParentId == 0) {
                    item.child = [];
                    flist.push(item);
                }
            });
            flist.forEach((v: any) => {
                list.forEach((item: any) => {
                    if (item.FTypeParentId === v.FId) {
                        v.child.push(item);
                    }
                });
                if(v.child.length) {
                    v.child.unshift({
                        FId: v.FId,
                        FTypeParentId: v.FTypeParentId,
                        FTypeName: '全部'
                    })
                }
            });
            console.log('9699999', flist);
            categories.value = flist;
            currentCategory.value = flist[0].FId;
        } catch(err:any) {
            console.error(err);
        }
        onRefresh()
    });
}




const keyword = ref('');
const pager = ref({
    index: 1,
    size: 20,
    total: 0,
    max: false,
    noData: false,
    loading: false,
})
const proList = ref<any[]>([]);
const getProList = (complete?: Function) => {

    let data = {
        orderType: 'B',  // 0商品 1服务
        storeNo: pageData.storeNo || Store.state.shop.storeNo,
        typeId: currentCategory.value,
        pageIndex: pager.value.index,
        pageSize: pager.value.size,
        userId: Store.state.user.account.userId || '',
        productShowFlag: '规格',
        sortType: '',
        startPrice: '',
        endPrice: '',
        word: keyword.value,
        serverSysUserId: pageData.linkSysUserId || '',
    };

    return getProductSkuByTypeid(data, {
        loadingIcon: false,
        complete: complete
    }).then(res => {
        const goodsList = res.data;
        if(res.data.list.length > 0) {
            res.data.list.forEach((item: any)=> {
                if(item.proImg) {
                    item.proImg = item.proImg + '_100A80w'
                }
            })
        }
        if(res.data.pageNum == 1) {
            proList.value = res.data.list;
        } else {
            proList.value.concat(...res.data.list);
        }
        proList.value.forEach((item: any)=> {
            item.num = 0;
            if(item.skuOption && typeof item.skuOption == 'string') {
                try {
                    item.skuOption = JSON.parse(item.skuOption)
                } catch(err) {
                    item.skuOption = ''
                }
            }
        })
    });
}

// 重头第一页刷新列表
function onRefresh(complete?: Function) {
    pager.value.loading = true
    pager.value.max = false
    pager.value.noData = false
    pager.value.index = 1
    proList.value = []
    getProList(() => {
        pager.value.loading = false;
        complete && typeof complete == 'function' && complete()
        uni.stopPullDownRefresh()
    })
}
// 滚动到底部加载
function onInfinite() {
    if (pager.value.loading || pager.value.max) return
    pager.value.loading = true
    pager.value.index += 1
    getProList(() => {
        pager.value.loading = false
    })
}


const isGreater = (a: string | number, b: string | number) => {
    a = +(a || 0)
    b = + (b || 0)
    return a > b
}


const goDetail = (item: any) => {
    uni.navigateTo({
        url: `/pages/product/detail?proId=${item.proId}&storeNo=${pageData.storeNo || Store.state.shop.storeNo}`
    });
};


</script>

<style lang="scss">
.container {
    min-height: 100vh;
    background-color: #f8f8f8;
}

.search-wrap {
    background-color: #eee;
    padding: 10rpx 30rpx;

    .search-box {
        display: flex;
        align-items: center;
        background-color: #fff;
        height: 60rpx;
        border-radius: 35rpx;
        padding: 0 30rpx;

        input {
            flex: 1;
            font-size: 28rpx;
        }
    }
}

.main-content {
    display: flex;
    height: calc(100vh - 110rpx);
}

.side-category {
    width: 200rpx;
    background-color: #eee;
    height: 100%;
    overflow-y: auto;

    .category-item {
        padding: 30rpx 20rpx;
        text-align: center;
        font-size: 26rpx;
        color: #333;
        position: relative;

        &.active {
            background-color: #fff;
            color: $baseColor;
            font-weight: bold;

            &::before {
                content: '';
                position: absolute;
                left: 5rpx;
                top: 50%;
                transform: translateY(-50%);
                width: 8rpx;
                height: 36rpx;
                background-color: $baseColor;
            }
        }
    }
}

.right-content {
    flex: 1;
    overflow-y: auto;
    background-color: #fff;
}

.sub-category {
    background: #fff;
    border-bottom: 1rpx solid #ddd;
    height: 90rpx;


    .scroll-view {
        width: 100%;
        white-space: nowrap;
    }

    .nav-item {
        display: inline-block;
        padding: 0 20rpx;
        margin-right: 20rpx;
        margin-top: 15rpx;
        font-size: 28rpx;
        color: #333;
        position: relative;
        height: 60rpx;
        line-height: 60rpx;
        background-color: #eee;
        border-radius: 20rpx;
        &.active {
            color: $baseColor;
            font-weight: bold;
        }
    }
}

.product-list {
    padding: 20rpx;

    .product-item {
        display: flex;
        background: #fff;
        padding: 20rpx;
        margin-bottom: 20rpx;
        border-radius: 12rpx;
        border-bottom: 1px solid #ddd;
        .product-img {
            width: 150rpx;
            height: 150rpx;
            border-radius: 8rpx;
        }

        .product-info {
            flex: 1;
            margin-left: 20rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            .zhima {
                display: flex;
                align-items: center;
                width: fit-content;
                height: 36rpx;
                line-height: 36rpx;
                background-color: #1890ff;
                color: #fff;
                font-size: 24rpx;
                padding: 0 10rpx;
                border-radius: 4rpx;
                margin-top: 5rpx;
                .zhima-icon {
                    width: 20rpx;
                    height: 22rpx;
                    flex-shrink: 0;
                    margin-right: 6rpx;
                }
            }
            .product-name {
                font-size: 28rpx;
                color: #333;
                font-weight: bold;
            }

            .product-desc {
                font-size: 24rpx;
                color: #999;
                margin: 10rpx 0;
            }

            .product-price {
                .price {
                    font-size: 32rpx;
                    color: $baseColor;
                    font-weight: bold;
                }
                .price-old{
                    font-size: 26rpx;
                    color: #999;
                    font-weight: normal;
                    text-decoration: line-through;
                    margin-left: 10rpx;
                }
            }
        }
    }
}
</style>
